import {BACKEND_ERROR_CODE, createFlatRequest, createRequest} from '@sa/axios';
import {localStg} from '@/utils/storage';
import {createProxyPattern, createServiceConfig} from '~/env.config';
import {useAuthStore} from "@/store/modules/auth";
import FileSaver from 'file-saver'
import http from "@/components/f_flow/api";


const {baseURL, otherBaseURL} = createServiceConfig(import.meta.env);

const isHttpProxy = import.meta.env.VITE_HTTP_PROXY === 'Y';

//正式请求
export const request = createFlatRequest<App.Service.Response>(
  {
    baseURL: isHttpProxy ? createProxyPattern() : baseURL,
    headers: {}
  },
  {
    async onRequest(config) {
      const {headers} = config;

      //设置请求token
      const token = localStg.get('token');
      const Authorization = token ? `Bearer ${token}` : null;
      Object.assign(headers, {Authorization});

      return config;
    },
    isBackendSuccess(response) {
      //请求成功判断
      return response.data.code === 'success';
    },
    async onBackendFail(_response) {
      //请求失败操作
    },
    transformBackendResponse(response) {
      return response.data.data;
    },
    onError(error) {
      //当请求失败时，显示错误消息
      let message = error.message;
      //显示后端错误信息
      if (error.code === BACKEND_ERROR_CODE) {
        message = error.response?.data?.msg || message;
      }
      window.$message?.error(message);
      if (error.response?.data?.code === '1003') {
        const authStore = useAuthStore();
        authStore.resetStore();
      }
    }
  }
);

export const download = async (url: string, name: string, data: object) => {
  //设置请求token
  const token = localStg.get('token');
  const Authorization = token ? `Bearer ${token}` : null;
  const res = await http.download(isHttpProxy ? createProxyPattern() + url : baseURL + url, data, {
    headers: {
      Authorization
    }
  })
  FileSaver.saveAs(
    new Blob([res], {type: 'application/octet-stream;charset=utf-8'}),
    name
  )
}

//demo请求
export const demoRequest = createRequest<App.Service.DemoResponse>(
  {
    baseURL: isHttpProxy ? createProxyPattern('demo') : otherBaseURL.demo
  },
  {
    async onRequest(config) {
      const {headers} = config;

      //设置请求token
      const token = localStg.get('token');
      const Authorization = token ? `Bearer ${token}` : null;
      Object.assign(headers, {Authorization});
      return config;
    },
    isBackendSuccess(response) {
      //请求成功判断
      return response.data.status === '200';
    },
    async onBackendFail(_response) {
      //请求失败操作
    },
    transformBackendResponse(response) {
      return response.data.result;
    },
    onError(error) {
      //当请求失败时，显示错误消息
      let message = error.message;
      if (error.code === BACKEND_ERROR_CODE) {
        message = error.response?.data?.message || message;
      }

      window.$message?.error(message);
    }
  }
);
